package com.matrix.draft.sockettest.http;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;

import java.net.URI;
import java.nio.charset.StandardCharsets;

public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        // 是否是HTTP请求
        if (msg instanceof HttpRequest) {
            // 统计服务器接收到的HTTP请求数量
            HttpServer.nRequests++;
            // 用户发过来的包转成HttpRequest对象
            HttpRequest request = (HttpRequest) msg;
            URI uri = new URI(request.uri());
            // 不响应/favicon.ico请求
            if ("/favicon.ico".equals(uri.getPath())) {
                return;
            }
            // 准备数据
            byte[] bytes = ("<h1 style='color:red;text-align:center;'>你好,我是Netty HTTP,网站已被请求" + HttpServer.nRequests + "次</h1>").getBytes(StandardCharsets.UTF_8);
            // 准备响应
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html;charset=utf-8");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, bytes.length);
            response.content().writeBytes(bytes);
            // 响应
            ctx.writeAndFlush(response);
            // 响应之后关闭
            ctx.close();
        }
    }
}
